package nsn.message.aggregator.commands;

import java.util.Map;



import nsn.message.aggregator.model.IMessageAggregator;
import nsn.message.aggregator.wizzards.AddSourceWizard;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.handlers.HandlerUtil;

/**
 * 
 * 
 * @author Lukasz Nowak
 * @since 10-03-2011
 * 
 */
public class AddSourceHandler extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		final IWorkbenchSite site = HandlerUtil.getActiveSite(event);
			final IMessageAggregator model = //
				(IMessageAggregator) site.getService(IMessageAggregator.class);
			final AddSourceWizard wizard = new AddSourceWizard(model);
			final Shell shell = HandlerUtil.getActiveShell(event);
			final WizardDialog dialog = new WizardDialog(shell, wizard);
			dialog.open();

			if (dialog.getReturnCode() == Window.OK) {
				final Map<String, String> params = wizard.getValues();
				final Job job = new Job("Adding ...") {

					@Override
					protected IStatus run(IProgressMonitor monitor) {
						monitor.setTaskName(getName());
						wizard.getSourceType().create(params);
						monitor.done();
						return Status.OK_STATUS;
					}
				};
				job.schedule();
			}

		return null;
	}

}
